package com.softwareinlife.xmpp.client;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * XMPP Client for Android
 * 
 * @author jangsunjin
 * 
 */
public class MainActivity extends Activity {
	/**
	 * XMPP Log Tag
	 */
	private static final String LOG_TAG = "XMPP";
	
	/**
	 * JID
	 */
	private String jid = null;

	/**
	 * Password
	 */
	private String pwd = null;

	/**
	 * TextView
	 */
	private TextView textView = null;

	/**
	 * Handler
	 */
	private Handler handler = null;

	/**
	 * XMPP Connection
	 */
	private XMPPConnection xmpp = null;

	/**
	 * Message Listener
	 */
	private MessageListener messageListener = null;

	/**
	 * String Buffer
	 */
	private StringBuffer sb = null;
	
	/**
	 * Edit Text
	 */
	private EditText editText3 = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		EditText jidComp = (EditText) findViewById(R.id.EditText01);
		EditText pwdComp = (EditText) findViewById(R.id.EditText02);

		jid = jidComp.getText().toString();
		pwd = pwdComp.getText().toString();
		Log.d(LOG_TAG, jid + ", " + pwd);
		
		editText3 = (EditText) findViewById(R.id.EditText03);

		Button connect = (Button) findViewById(R.id.Button01);
		connect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(LOG_TAG, v + " was clicked!");
				connect();
			}
		});

		textView = (TextView) findViewById(R.id.TextView01);

		messageListener = new MessageListener() {
			public void processMessage(Chat chat, Message message) {
				textView.setText("Received message: " + message.getBody()
						+ "\n");
				textView.append("(" + message.getFrom() + ", "
						+ message.getTo() + ")\n");
				textView.setTextColor(Color.WHITE);

				Log.v(LOG_TAG, "Received message: " + message);
				Log.v(LOG_TAG, "Received message: " + message.getBody());
				Log.v(LOG_TAG, "Received message: " + message.getFrom());
				Log.v(LOG_TAG, "Received message: " + message.getPacketID());
				Log.v(LOG_TAG, "Received message: " + message.getSubject());
				Log.v(LOG_TAG, "Received message: " + message.getTo());
				Log.v(LOG_TAG, "Received message: " + message.getXmlns());
			}
		};

		sb = new StringBuffer();
	}

	/**
	 * Connect to XMPP Server
	 */
	protected void connect() {
		handler = new Handler() {
			@Override
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);

				textView.append(textView.getText() + "\n" + sb.toString());
			}
		};

		handler.post(new Runnable() {
			public void run() {
				SASLAuthentication.unregisterSASLMechanism("PLAIN");
				SASLAuthentication.registerSASLMechanism("PLAIN",
						GoogleSASLPlainMechanism.class);

				ConnectionConfiguration connConfig = new ConnectionConfiguration(
						"talk.google.com", 5222, "gmail.com");

				xmpp = new XMPPConnection(connConfig);
				try {
					xmpp.connect();

					// for other jabber accounts, truncate after the @
					// xmpp.login("username", "password");

					// for gtalk / gmail, include the @
					xmpp.login(jid, pwd);
					Log.v(LOG_TAG, "Log in");
				} catch (XMPPException e) {
					Log.v(LOG_TAG, "Failed to connect to " + xmpp.getHost());
					e.printStackTrace();
				}

				try {
					Chat chat = xmpp.getChatManager().createChat(
							"xmppsoftwareinlife@appspot.com", messageListener);
					chat.sendMessage(editText3.getText().toString());
				} catch (XMPPException e) {
					Log.v(LOG_TAG, "Chat exception is " + e);
					e.printStackTrace();
				}

				// Accept only messages from friend@gmail.com
				PacketFilter filter = new AndFilter(new PacketTypeFilter(
						Message.class), new FromContainsFilter(
						"xmppsoftwareinlife@appspot.com"));

				// Collect these messages
				PacketCollector collector = xmpp.createPacketCollector(filter);

				Packet packet = collector.nextResult();

				if (packet instanceof Message) {
					// Process message
					Message msg = (Message) packet;
					Log.v(LOG_TAG, "Got message:" + msg.getBody());

					sb.append(msg.getBody() + "\n");

					handler.sendEmptyMessage(0);
				}
			}
		});
	}

	/**
	 * Show Text
	 * 
	 * @param msg
	 */
	public void showText(Message msg) {
		textView.append("Got message:" + msg.getBody());
	}
}